package com.alquimia.identityaccess.rest.controller;

import com.alquimia.identityaccess.application.events.user.RegisterUserEvent;
import com.alquimia.identityaccess.application.events.user.UserRegisteredEvent;
import com.alquimia.identityaccess.application.services.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Created by Ivo on 14/07/2014.
 */
@Controller
@RequestMapping("/signup")
public class RegisterUserCommandController {

    private static Logger LOG = LoggerFactory.getLogger(RegisterUserCommandController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<UserRegisteredEvent> registerUser(@RequestBody RegisterUserEvent registerUserEvent, UriComponentsBuilder builder) {

        UserRegisteredEvent userRegisteredEvent = userService.registerUser(registerUserEvent);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(
                builder.path("/users/{userId}")
                        .buildAndExpand(userRegisteredEvent.getUserId()).toUri()
        );

        return new ResponseEntity<UserRegisteredEvent>(userRegisteredEvent, headers, HttpStatus.CREATED);
    }

}
